<template>
    <div ref="chartRef" :style="{ width: width, height: height }"></div>
  </template>
  
  <script setup>
  import * as echarts from 'echarts';
  
  const props = defineProps({
    width: { type: String, default: '100%' },
    height: { type: String, default: '400px' },
    options: { type: Object, default: () => ({}) }
  });
  
  const chartRef = ref(null);
  let chartInstance = null;
  
  // 定义窗口 resize 事件的处理函数
  const handleWindowResize = () => {
    if (chartInstance) {
      chartInstance.resize();
    }
  };
  onMounted(() => {
    chartInstance = echarts.init(chartRef.value);
    chartInstance.setOption(props.options);
    // 添加窗口 resize 事件监听器
    window.addEventListener('resize', handleWindowResize);
  });
  
  watch(() => props.options, (newOptions) => {
    if (chartInstance) {
      chartInstance.setOption(newOptions);
    }
  }, { deep: true });
  
  onBeforeUnmount(() => {
    if (chartInstance) {
      chartInstance.dispose();
      chartInstance = null;
    }
    // 移除窗口 resize 事件监听器
    window.removeEventListener('resize', handleWindowResize);
  });
  </script>
  
  <style scoped>
  /* 确保图表容器可以自适应缩放 */
  div {
    width: 100%;
    height: 100%;
    min-width: 0; /* 避免最小宽度限制 */
    min-height: 0; /* 避免最小高度限制 */
  }
  </style>